package com.example.awake_android

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.view.FlutterView
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    var flutterFragment: MyFlutterFragment? = null

    private var mMessageChannel: BasicMessageChannel<Any>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //显示flutter界面
        button2.setOnClickListener {
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            flutterFragment = flutterFragment ?: MyFlutterFragment()
            fragmentTransaction.replace(
                R.id.fl_flutter_view,
                flutterFragment ?: MyFlutterFragment()
            )
            fragmentTransaction.commit()
        }

        //点击发送给flutter，交易界面显示
        button3.setOnClickListener {
            messageChannelFunction()
            mMessageChannel?.send(
                "我来自客户端，点击我给客户端发消息"
            ) { p0 ->
                Toast.makeText(this@MainActivity, p0.toString(), Toast.LENGTH_LONG).show()
            }
        }

    }

    private fun messageChannelFunction() {
        //消息接收监听
        //BasicMessageChannel （主要是传递字符串和一些半结构体的数据）
        //创建通
        mMessageChannel = mMessageChannel ?: BasicMessageChannel<Any>(
            flutterFragment?.view as FlutterView,
            flutterFragment!!.CHANNEL,
            StandardMessageCodec.INSTANCE
        );
        // 接收消息监听
        mMessageChannel?.setMessageHandler(object : BasicMessageChannel.MessageHandler<Any> {
            override fun onMessage(p0: Any?, p1: BasicMessageChannel.Reply<Any>) {
                val arguments = p0 as Map<*, *>
                val ss = arguments["method"] as String
                Toast.makeText(this@MainActivity, "客户端收到消息: $ss", Toast.LENGTH_LONG).show()
            }
        });

    }
}
